// 配置axios基本的属性

const axios = require('axios')
axios.defaults.baseURL = 'http://127.0.0.1:8000' // 请求的接口主域名
axios.defaults.timeout = 10000 // 请求超时的设置 10s

// 请求拦截器(在请求前会自动去做的操作)，如果登陆了，那么自动带token发送
axios.interceptors.request.use(config => {
  let token = localStorage.getItem('token');
  if (token) {
    // axios.defaults.headers['Authorization'] = token // 头部设置
    config.headers.common['Authorization'] = "JWT " + token // 头部设置
  }
  return config;
}, error => {
  console.log(error)
  return Promise.reject(error);
});

// 响应拦截器(在响应时自动会做的操作)，比如状态码返回为401时，要进入login界面
axios.interceptors.response.use(response => {
  return response;
}, error => {
  console.log(error.request.response)
  if (error.request.status == 401) {
    window.location.href = "/"
  }
  return error
});


/**
 * post方法，对应post请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 * @param {Object} headers [请求时的头部]
 **/
export function get(url, params, headers) {
  return new Promise((resolve, reject) => {
    axios.get(url, {params, headers}).then(res => {
      resolve(res)
    }).catch(err => {
      reject(err)
    })
  })
}

export function post(url, params, headers) {
  return new Promise((resolve, reject) => {
    axios.post(url, params, headers).then((res) => {
      resolve(res)
    }).catch((err) => {
      // debugger
      reject(err)
    })
  })
}


export function put(url, params, headers) {
  return new Promise((resolve, reject) => {
    axios.put(url, params, headers).then((res) => {
      resolve(res)
    }).catch((err) => {
      // debugger
      reject(err)
    })
  })
}

export function del(url, params, headers) {
  return new Promise((resolve, reject) => {
    axios.delete(url, {data: params, headers}).then((res) => {
      resolve(res)
    }).catch((err) => {
      // debugger
      reject(err)
    })
  })
}

export default axios;
